package com.limh.jkzs.util;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

/**
 * Function:
 * author: limh
 * time:2017/11/21
 */

public class GsonUtils {
    private static Gson gson = null;

    static {
        if (null == gson) {
            gson = new Gson();
        }
    }

    /**
     * 类对象转String
     *
     * @param obj 类型类
     * @return Str
     */
    public static String gson2Str(Object obj) {
        String str = null;
        if (null != gson) {
            str = gson.toJson(obj);
        }
        return str;
    }

    /**
     * Str转JavaBean
     *
     * @param gsonString gsonString
     * @param cls        Bean
     * @param <T>        t
     * @return JavaBean
     */
    public static <T> T str2Bean(String gsonString, Class<T> cls) {
        T t = null;
        if (null != gson) {
            t = gson.fromJson(gsonString, cls);
        }
        return t;
    }

    /**
     * List转jsonString
     *
     * @param t   Bean类型
     * @param <T> 实体泛型
     * @return String
     */
    public static <T> String list2Str(List<T> t) {
        JSONArray array = new JSONArray();
        for (T item : t) {
            array.put(gson2Str(item));
        }
        return array.toString();
    }

    /**
     * gonString转List
     * @param gsonString str类型
     * @param cls 类类型
     * @param <T> 泛型
     * @return List
     */
    public static <T> List<T> str2List(String gsonString, Class<T> cls) {
        List<T> data = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(gsonString);
            for (int i = 0; i < array.length(); i++) {
                data.add(str2Bean((String) array.get(i), cls));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return data;
    }

}
